<template>
  <div class="container">
    <div class="main">
      <div class="header">
        <el-button type="primary" @click="openDialog(null)">新建</el-button>
        <el-button type="success" @click="importData">导入</el-button>
        <el-button type="danger" @click="batchDelete">批量删除</el-button>
        <el-select v-model="selectedFilter" @change="handleFilterChange">
          <el-option label="启用" value="1"></el-option>
          <el-option label="禁用" value="0"></el-option>
        </el-select>
        <el-input placeholder="请输入关键字搜索" v-model="searchTable" />
        <el-button type="info" @click="query" style="background-color: orange;">查询</el-button>
        <el-button type="info" @click="reset">重置</el-button>
      </div>
      <el-table :empty-text="emptyText" :data="tableData" border class="eltable" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column type="index"  label="序号" width="60"></el-table-column>
        <el-table-column prop="ks_id" v-if="false"></el-table-column>
        <el-table-column prop="ks_code" label="客商编码" width="100"></el-table-column>
        <el-table-column prop="ks_name" label="客商名称" width="100"></el-table-column>
        <el-table-column prop="ks_type_name" label="客商类型" width="85"></el-table-column>
        <el-table-column prop="ks_jc" label="客商简称" width="85"></el-table-column>
        <el-table-column prop="ks_level_name" label="客商等级" width="85"></el-table-column>
        <el-table-column prop="ks_sx_name" label="客商属性" width="120"></el-table-column>
        <el-table-column prop="ks_hy_name" label="客商行业"width="85" ></el-table-column>
        <el-table-column prop="ks_person" label="联系人" ></el-table-column>
        <el-table-column prop="ks_phone" label="电话" ></el-table-column>
        <el-table-column prop="ks_cz" label="传真" ></el-table-column>
        <el-table-column prop="ks_email" label="邮箱" ></el-table-column>
        <el-table-column prop="ks_address" label="地址" ></el-table-column>
        <el-table-column prop="ks_gj_name" label="国家" width="60"></el-table-column>
        <el-table-column label="启用" width="70">
          <template #default="{ row }">
            <el-switch v-model="row.ks_state" :active-value="1" :inactive-value="0" @change="updateState(row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="{ row }">
            <el-button type="text" @click="openDialog(row)">编辑</el-button>
            <el-button type="text" @click="deleteRow(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 新增/编辑弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px" @close="resetForm">
  <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px">
    <el-row gutter="20">
      <el-col :span="12">
        <el-form-item label="客商编码：" prop="ks_code">
          <el-input v-model="formData.ks_code"  :readonly="true"  />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="客商名称：" prop="ks_name">
          <el-input v-model="formData.ks_name" placeholder="请输入名称" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row gutter="20">
      <el-col :span="12">
        <el-form-item label="客商分类：" prop="ks_type">
          <el-select v-model="formData.ks_type" placeholder="请选择" clearable>
            <el-option v-for="item in categoryOptions" :key="item.dictionary_id" :label="item.dictionary_name" :value="item.dictionary_id" />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="客商简称：" prop="ks_jc">
          <el-input v-model="formData.ks_jc" placeholder="请输入简称" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row gutter="20">
      <el-col :span="12">
        <el-form-item label="客商等级：" prop="ks_level">
          <el-select v-model="formData.ks_level" placeholder="请选择" clearable>
            <el-option v-for="item in levelOptions" :key="item.dictionary_id" :label="item.dictionary_name" :value="item.dictionary_id" />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="客商属性：" prop="ks_sx">
          <el-select v-model="formData.ks_sx" placeholder="请选择" clearable>
            <el-option v-for="item in attributeOptions" :key="item.dictionary_id" :label="item.dictionary_name" :value="item.dictionary_id" />
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row gutter="20">
      <el-col :span="12">
        <el-form-item label="客商行业：" prop="ks_hy">
          <el-select v-model="formData.ks_hy" placeholder="请选择" clearable>
            <el-option v-for="item in industryOptions" :key="item.dictionary_id" :label="item.dictionary_name" :value="item.dictionary_id" />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="联系人：" prop="ks_person">
          <el-input v-model="formData.ks_person" placeholder="请输入联系人" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row gutter="20">
      <el-col :span="12">
        <el-form-item label="电话：" prop="ks_phone">
          <el-input v-model="formData.ks_phone" placeholder="请输入电话" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="传真：" prop="ks_cz">
          <el-input v-model="formData.ks_cz" placeholder="请输入传真" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row gutter="20">
      <el-col :span="12">
        <el-form-item label="邮箱：" prop="ks_email">
          <el-input v-model="formData.ks_email" placeholder="请输入邮箱" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="地址：" prop="ks_address">
          <el-input v-model="formData.ks_address" placeholder="请输入地址" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row gutter="20">
      <el-col :span="12">
        <el-form-item label="国家：" prop="ks_gj">
          <el-select v-model="formData.ks_gj" placeholder="请选择" clearable>
            <el-option v-for="item in countryOptions" :key="item.dictionary_id" :label="item.dictionary_name" :value="item.dictionary_id" />
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
  <template #footer>
    <el-button @click="dialogVisible = false">取消</el-button>
    <el-button type="primary" @click="submitForm">保存</el-button>
  </template>
</el-dialog>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';

export default {
  setup() {
    const emptyText = '暂无数据';
    const selectedFilter = ref('1');
    const searchTable = ref('');
    const tableData = ref([]);
    const multipleSelection = ref([]);
    const dialogVisible = ref(false);
    const dialogTitle = ref('新增客商');
    const formRef = ref(null);
    const formData = ref({
      ks_code: '',
      ks_name: '',
      ks_type: null,
      ks_jc: '',
      ks_level: null,
      ks_sx: null,
      ks_hy: null,
      ks_person: '',
      ks_phone: '',
      ks_cz: '',
      ks_email: '',
      ks_address: '',
      ks_gj: null,
    });

    const industryOptions = ref([]);
    const categoryOptions = ref([]);
    const levelOptions = ref([]);
    const attributeOptions = ref([]);
    const countryOptions = ref([]);

    const formRules = {
      ks_name: [{ required: true, message: '请输入客商名称', trigger: 'blur' }],
      ks_type: [{ required: true, message: '请选择客商分类', trigger: 'change' }],
      ks_jc: [{ required: true, message: '请输入客商简称', trigger: 'blur' }],
      ks_level: [{ required: true, message: '请选择客商等级', trigger: 'change' }],
      ks_sx: [{ required: true, message: '请选择客商属性', trigger: 'change' }],
      ks_hy: [{ required: true, message: '请选择客商行业', trigger: 'change' }],
      ks_person: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
      ks_phone: [{ required: true, message: '请输入电话', trigger: 'blur' }],
      ks_address: [{ required: true, message: '请输入地址', trigger: 'blur' }],
      ks_gj: [{ required: true, message: '请选择国家', trigger: 'change' }],
    };

    const fetchTableData = () => {
      axios.get(`/api/KS/GetKS?state=${selectedFilter.value}`)
        .then(res => {
          tableData.value = res.data;
        })
        .catch(err => {
          console.error('Error fetching data:', err);
          ElMessage.error('加载数据失败，请稍后再试');
        });
    };
    
    // 选中行变化
    const handleSelectionChange = (val) => {
      multipleSelection.value = val;
    };
    
    // 筛选条件变化
    const handleFilterChange = () => {
      fetchTableData();
    };

    // 更新状态
    const updateState = (row) => {
      ElMessageBox.confirm('改变状态, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.put(`/api/KS/StateChange?id=${row.ks_id}&state=${row.ks_state}`)
          .then(response => {
            if (response.data === true) {
              ElMessage.success('状态已更新');
            } else {
              ElMessage.error('更新失败，后端返回错误');
            }
            fetchTableData();
          })
          .catch(err => {
            console.error('Error:', err);
            ElMessage.error('更新失败');
          });
      }).catch(() => {
        fetchTableData();
        ElMessage.info('已取消改变');
      });
    };

    // 查询
    const query = () => {
      searchTableData(); // 假设后端支持关键字搜索，需传递searchTable.value
    };
    
    const searchTableData = () => {
      if (!searchTable.value) {
        fetchTableData();
        return;
      }
      const params = {
        state: selectedFilter.value,
        str: searchTable.value
      };
      axios.get('/api/KS/GetKS', { params })
        .then(res => {
          tableData.value = res.data;
        })
        .catch(err => {
          console.error('Error fetching data:', err);
          ElMessage.error('加载数据失败，请稍后再试');
        });
    };
    
    // 重置
    const reset = () => {
      searchTable.value = '';
      selectedFilter.value = '1';
      fetchTableData();
    };

    // 删除单行
    const deleteRow = (row) => {
      ElMessageBox.confirm('此操作将删除该列信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.put(`/api/KS/DelKS?id=${row.ks_id}`)
          .then(response => {
            if (response.data === true) {
              ElMessage.success("删除成功");
              fetchTableData();
            } else {
              ElMessage.error("删除失败：后端返回失败");
            }
          })
          .catch(err => {
            console.error('删除失败:', err);
            ElMessage.error("删除失败：请求异常");
          });
      }).catch(() => {
        ElMessage.info("已取消删除");
      });
    };

    const batchDelete = async () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning("请先选择要删除的项");
    return;
  }
  try {
    await ElMessageBox.confirm('此操作将删除选中的项, 是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    const selectedIds = multipleSelection.value.map(item => item.ks_id); // 确保 ks_id 是后端需要的字段
    const response = await axios.put('/api/KS/DelKSs', selectedIds, {
      headers: {
        'Content-Type': 'application/json'
      }
    });
    if (response.data === true) {
      ElMessage.success("批量删除成功");
      fetchTableData();
    } else {
      ElMessage.error("批量删除失败：后端返回失败");
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error("批量删除失败");
    } else {
      ElMessage.info("已取消批量删除");
    }
  }
};

    const fetchDictOptions = async (type) => {
      try {
        const res = await axios.get(`/api/Dict/GetOneDict?id=${encodeURIComponent(type)}`);
        return res.data;
      } catch (err) {
        console.error(`获取${type}失败:`, err);
        return [];
      }
    };

    const openDialog = async (row) => {
      if (row) {
        formData.value = { ...row };
        dialogTitle.value = '编辑客商';
      } else {
        const now = new Date();
        const year = now.getFullYear();
        const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要加1并补零
        const day = String(now.getDate()).padStart(2, '0'); // 补零

        // 生成四位随机数
        const randomNumber = Math.floor(1000 + Math.random() * 9000); // 生成1000到9999之间的随机数

        // 拼接时间字符串和随机数
        const formattedTime = `${year}${month}${day}`;
        let code = `KS${formattedTime}${randomNumber}`;

        formData.value = {
          ks_code: code,
          ks_name: '',
          ks_type: null,
          ks_jc: '',
          ks_level: null,
          ks_sx: null,
          ks_hy: null,
          ks_person: '',
          ks_phone: '',
          ks_cz: '',
          ks_email: '',
          ks_address: '',
          ks_gj: null,
        };
        dialogTitle.value = '新增客商';
      }

      const [industry, category, level, attribute, country] = await Promise.all([
        fetchDictOptions(3),
        fetchDictOptions(4),
        fetchDictOptions(2),
        fetchDictOptions(1),
        fetchDictOptions(5),
      ]);

      industryOptions.value = industry;
      categoryOptions.value = category;
      levelOptions.value = level;
      attributeOptions.value = attribute;
      countryOptions.value = country;

      dialogVisible.value = true;
    };

    const submitForm = async () => {
  try {
    await formRef.value.validate(); // 验证表单

    let response;
    if (formData.value.ks_id) {
      // 编辑模式，调用更新 API
      response = await axios.put('/api/KS/UpdateKS', {
        ...formData.value,
      });
    } else {
      // 新增模式，调用新增 API
      response = await axios.post('/api/KS/AddKS', {
        ...formData.value,
        ks_id: 0, // 新增时 ks_id 设为 0
        ks_state: formData.value.ks_state || 0, // 默认状态
      });
    }

    if (response.data) {
      ElMessage.success(formData.value.ks_id ? '编辑成功' : '新增成功');
      dialogVisible.value = false;
      fetchTableData(); // 刷新表格数据
    } else {
      ElMessage.error('操作失败：后端返回失败');
    }
  } catch (err) {
    console.error('操作失败:', err);
    ElMessage.error('操作失败');
  }
};

    const resetForm = () => {
      formRef.value.resetFields();
    };

    onMounted(() => {
      fetchTableData();
    });

    return {
      searchTableData,
      handleSelectionChange,
      handleFilterChange,
      updateState,
      query,
      reset,
      deleteRow,
      batchDelete,
      emptyText,
      selectedFilter,
      searchTable,
      tableData,
      multipleSelection,
      dialogVisible,
      dialogTitle,
      formRef,
      formData,
      formRules,
      industryOptions,
      categoryOptions,
      levelOptions,
      attributeOptions,
      countryOptions,
      fetchTableData,
      openDialog,
      submitForm,
      resetForm,
    };
  },
};
</script>

<style scoped>
.container {  
  display: flex;  
  gap: 20px;
  height: 95%;
}  

.sidebar {  
  height: 100%;
  
}  

.main {  
  width: 80%;
  flex: 1;  
  height: 100%;
}  

.header {  
   display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 20px;
}  
.eltable{
  height: 95%;
}
.letree{
  height: 100%;
}
.demo-form-inline .el-input {
  --el-input-width: 200px;
}

.demo-form-inline .el-select {
  --el-select-width: 200px;
}
</style>